using System;
using System.Drawing;
using System.Xml.Serialization;
using System.IO;
using GomokuGame.AI;

namespace GomokuGame
{
    /// <summary>
    /// 游戏设置类
    /// </summary>
    [Serializable]
    public class GameSettings
    {
        #region 游戏设置
        /// <summary>
        /// 棋盘大小
        /// </summary>
        public int BoardSize { get; set; } = 15;
        
        /// <summary>
        /// 落子音效开关
        /// </summary>
        public bool SoundEnabled { get; set; } = true;
        
        /// <summary>
        /// 背景音乐开关
        /// </summary>
        public bool BackgroundMusicEnabled { get; set; } = false;
        
        /// <summary>
        /// 音效音量 (0-100)
        /// </summary>
        public int SoundVolume { get; set; } = 50;
        
        /// <summary>
        /// 背景音乐音量 (0-100)
        /// </summary>
        public int MusicVolume { get; set; } = 30;
        
        /// <summary>
        /// 界面主题
        /// </summary>
        public string Theme { get; set; } = "默认";
        
        /// <summary>
        /// 最大悔棋次数
        /// </summary>
        public int MaxUndoCount { get; set; } = 10;
        
        /// <summary>
        /// 自动保存游戏记录
        /// </summary>
        public bool AutoSaveGameRecord { get; set; } = true;
        
        /// <summary>
        /// 保留游戏记录天数
        /// </summary>
        public int KeepGameRecordsDays { get; set; } = 30;
        #endregion

        #region AI设置
        /// <summary>
        /// 默认AI难度
        /// </summary>
        public AIDifficulty DefaultAIDifficulty { get; set; } = AIDifficulty.Intermediate;
        
        /// <summary>
        /// AI思考时间限制（毫秒）
        /// </summary>
        public int AITimeLimit { get; set; } = 3000;
        
        /// <summary>
        /// AI搜索深度限制
        /// </summary>
        public int AISearchDepth { get; set; } = 4;
        
        /// <summary>
        /// AI是否显示思考进度
        /// </summary>
        public bool ShowAIThinkingProgress { get; set; } = true;
        
        /// <summary>
        /// AI策略参数 - 攻击权重
        /// </summary>
        public double AIAttackWeight { get; set; } = 1.0;
        
        /// <summary>
        /// AI策略参数 - 防守权重
        /// </summary>
        public double AIDefenseWeight { get; set; } = 0.8;
        
        /// <summary>
        /// AI策略参数 - 位置权重
        /// </summary>
        public double AIPositionWeight { get; set; } = 0.6;
        #endregion

        #region 界面设置
        /// <summary>
        /// 窗口宽度
        /// </summary>
        public int WindowWidth { get; set; } = 800;
        
        /// <summary>
        /// 窗口高度
        /// </summary>
        public int WindowHeight { get; set; } = 600;
        
        /// <summary>
        /// 窗口是否最大化
        /// </summary>
        public bool WindowMaximized { get; set; } = false;
        
        /// <summary>
        /// 棋盘背景颜色
        /// </summary>
        public Color BoardBackgroundColor { get; set; } = Color.FromArgb(222, 184, 135);
        
        /// <summary>
        /// 棋盘线条颜色
        /// </summary>
        public Color BoardLineColor { get; set; } = Color.Black;
        
        /// <summary>
        /// 黑棋子颜色
        /// </summary>
        public Color BlackPieceColor { get; set; } = Color.Black;
        
        /// <summary>
        /// 白棋子颜色
        /// </summary>
        public Color WhitePieceColor { get; set; } = Color.White;
        
        /// <summary>
        /// 棋子边框颜色
        /// </summary>
        public Color PieceBorderColor { get; set; } = Color.Gray;
        
        /// <summary>
        /// 最后落子标记颜色
        /// </summary>
        public Color LastMoveColor { get; set; } = Color.Red;
        
        /// <summary>
        /// 棋子样式
        /// </summary>
        public string PieceStyle { get; set; } = "圆形";
        
        /// <summary>
        /// 字体大小
        /// </summary>
        public float FontSize { get; set; } = 9.0f;
        
        /// <summary>
        /// 字体名称
        /// </summary>
        public string FontName { get; set; } = "微软雅黑";
        
        /// <summary>
        /// 是否显示网格线
        /// </summary>
        public bool ShowGridLines { get; set; } = true;
        
        /// <summary>
        /// 是否显示坐标
        /// </summary>
        public bool ShowCoordinates { get; set; } = false;
        
        /// <summary>
        /// 是否显示最后落子标记
        /// </summary>
        public bool ShowLastMove { get; set; } = true;
        #endregion

        #region 静态实例
        private static GameSettings _instance;
        private static readonly object _lock = new object();
        
        /// <summary>
        /// 获取设置实例（单例模式）
        /// </summary>
        public static GameSettings Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = LoadSettings();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion

        #region 保存和加载
        /// <summary>
        /// 设置文件路径
        /// </summary>
        private static string SettingsFilePath
        {
            get
            {
                string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string settingsDir = Path.Combine(documentsPath, "GomokuGame");
                Directory.CreateDirectory(settingsDir);
                return Path.Combine(settingsDir, "settings.xml");
            }
        }

        /// <summary>
        /// 保存设置到文件
        /// </summary>
        public void Save()
        {
            try
            {
                var serializer = new XmlSerializer(typeof(GameSettings));
                using (var writer = new StreamWriter(SettingsFilePath))
                {
                    serializer.Serialize(writer, this);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"保存设置失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 从文件加载设置
        /// </summary>
        private static GameSettings LoadSettings()
        {
            try
            {
                if (File.Exists(SettingsFilePath))
                {
                    var serializer = new XmlSerializer(typeof(GameSettings));
                    using (var reader = new StreamReader(SettingsFilePath))
                    {
                        return (GameSettings)serializer.Deserialize(reader);
                    }
                }
            }
            catch (Exception ex)
            {
                // 如果加载失败，返回默认设置
                System.Diagnostics.Debug.WriteLine($"加载设置失败：{ex.Message}");
            }
            
            // 返回默认设置
            return new GameSettings();
        }

        /// <summary>
        /// 重置为默认设置
        /// </summary>
        public void ResetToDefault()
        {
            var defaultSettings = new GameSettings();
            var properties = typeof(GameSettings).GetProperties();
            
            foreach (var property in properties)
            {
                if (property.CanWrite)
                {
                    property.SetValue(this, property.GetValue(defaultSettings));
                }
            }
        }
        #endregion

        #region 事件
        /// <summary>
        /// 设置更改事件
        /// </summary>
        public event EventHandler<SettingsChangedEventArgs> SettingsChanged;

        /// <summary>
        /// 触发设置更改事件
        /// </summary>
        /// <param name="settingName">设置名称</param>
        public void OnSettingsChanged(string settingName)
        {
            SettingsChanged?.Invoke(this, new SettingsChangedEventArgs { SettingName = settingName });
        }
        #endregion
    }

    /// <summary>
    /// 设置更改事件参数
    /// </summary>
    public class SettingsChangedEventArgs : EventArgs
    {
        public string SettingName { get; set; }
    }
} 